package org.jeecg.modules.business.transfer.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.modules.business.transfer.entity.PaperPurchase;
import org.jeecg.modules.business.transfer.entity.PaperPurchaseMaterial;
import org.jeecg.modules.business.transfer.entity.vo.PaperPurchaseParam;
import org.jeecg.modules.business.transfer.service.IPaperPurchaseMaterialService;
import org.jeecg.modules.business.transfer.service.IPaperPurchaseService;
import org.jeecg.modules.business.transfer.vo.PaperPurchasePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;


/**
 * @Description: 纸筒采购任务
 * @Author: jeecg-boot
 * @Date: 2023-11-14
 * @Version: V1.0
 */
@Api(tags = "纸筒采购任务")
@RestController
@RequestMapping("/business/paperPurchase")
@Slf4j
public class PaperPurchaseController {
    @Autowired
    private IPaperPurchaseService paperPurchaseService;
    @Autowired
    private IPaperPurchaseMaterialService wmsPaperPurchaseMaterialService;

    /**
     * 分页列表查询
     *
     * @param paperPurchase
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "纸筒采购任务-分页列表查询", notes = "纸筒采购任务-分页列表查询")
    @GetMapping(value = "/list")
    public Result<Page<PaperPurchase>> queryPageList(PaperPurchaseParam paperPurchase,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Result<Page<PaperPurchase>> result = new Result<>();
        Page<PaperPurchase> pageList = new Page<>(pageNo,pageSize);
        pageList = paperPurchaseService.listByPage(pageList, paperPurchase);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param paperPurchasePage
     * @return
     */
    @AutoLog(value = "纸筒采购任务-添加")
    @ApiOperation(value = "纸筒采购任务-添加", notes = "纸筒采购任务-添加")
    @RequiresPermissions("business:paperPurchase:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody PaperPurchasePage paperPurchasePage) {
        PaperPurchase paperPurchase = new PaperPurchase();
        BeanUtils.copyProperties(paperPurchasePage, paperPurchase);
        paperPurchaseService.saveMain(paperPurchase, paperPurchasePage.getWmsPaperPurchaseMaterialList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param paperPurchasePage
     * @return
     */
    @AutoLog(value = "纸筒采购任务-编辑")
    @ApiOperation(value = "纸筒采购任务-编辑", notes = "纸筒采购任务-编辑")
    @RequiresPermissions("business:paperPurchase:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody PaperPurchasePage paperPurchasePage) {
        PaperPurchase paperPurchase = new PaperPurchase();
        BeanUtils.copyProperties(paperPurchasePage, paperPurchase);
        PaperPurchase paperPurchaseEntity = paperPurchaseService.getById(paperPurchase.getId());
        if (paperPurchaseEntity == null) {
            return Result.error("未找到对应数据");
        }
        paperPurchaseService.updateMain(paperPurchase, paperPurchasePage.getWmsPaperPurchaseMaterialList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "纸筒采购任务-通过id删除")
    @ApiOperation(value = "纸筒采购任务-通过id删除", notes = "纸筒采购任务-通过id删除")
    @RequiresPermissions("business:paperPurchase:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        paperPurchaseService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "纸筒采购任务-通过id查询", notes = "纸筒采购任务-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<PaperPurchase> queryById(@RequestParam(name = "id", required = true) String id) {
        PaperPurchase paperPurchase = paperPurchaseService.getById(id);
        if (paperPurchase == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(paperPurchase);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "纸筒采购任务-物料主表ID查询", notes = "纸筒采购任务-物料-通主表ID查询")
    @GetMapping(value = "/queryWmsPaperPurchaseMaterialByMainId")
    public Result<List<PaperPurchaseMaterial>> queryWmsPaperPurchaseMaterialListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<PaperPurchaseMaterial> wmsPaperPurchaseMaterialList = wmsPaperPurchaseMaterialService.selectByMainId(id);
        return Result.OK(wmsPaperPurchaseMaterialList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param paperPurchase
     */
    @RequiresPermissions("business:paperPurchase:exportXls")
    @ApiOperation(value = "纸筒采购任务-导出excel", notes = "纸筒采购任务-导出excel")
    @GetMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, PaperPurchase paperPurchase) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<PaperPurchase> queryWrapper = QueryGenerator.initQueryWrapper(paperPurchase, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<PaperPurchase> paperPurchaseList = paperPurchaseService.list(queryWrapper);
        List<String> ids = paperPurchaseList.stream().map(PaperPurchase::getId).collect(Collectors.toList());
        List<PaperPurchaseMaterial> materials = wmsPaperPurchaseMaterialService.list(new LambdaQueryWrapper<PaperPurchaseMaterial>()
                .in(PaperPurchaseMaterial::getPaperPurchaseId, ids));
        Map<String, List<PaperPurchaseMaterial>> listMap = new HashMap<>();
        if (materials != null){
            listMap = materials.stream().collect(Collectors.groupingBy(PaperPurchaseMaterial::getPaperPurchaseId));
        }

        // Step.3 组装pageList
        List<PaperPurchasePage> pageList = new ArrayList<PaperPurchasePage>();
        for (PaperPurchase main : paperPurchaseList) {
            PaperPurchasePage vo = new PaperPurchasePage();
            BeanUtils.copyProperties(main, vo);
            List<PaperPurchaseMaterial> wmsPaperPurchaseMaterialList = listMap.get(main.getId());
            vo.setWmsPaperPurchaseMaterialList(wmsPaperPurchaseMaterialList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "纸筒采购任务列表");
        mv.addObject(NormalExcelConstants.CLASS, PaperPurchasePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("纸筒采购任务数据", "导出人:" + sysUser.getRealname(), "纸筒采购任务"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @ApiOperation(value = "纸筒采购任务-导入", notes = "纸筒采购任务-物料-导入")
    @RequiresPermissions("business:paperPurchase:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<PaperPurchasePage> list = ExcelImportUtil.importExcel(file.getInputStream(), PaperPurchasePage.class, params);
                for (PaperPurchasePage page : list) {
                    PaperPurchase po = new PaperPurchase();
                    BeanUtils.copyProperties(page, po);
                    paperPurchaseService.saveMain(po, page.getWmsPaperPurchaseMaterialList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    /**
     * 发送sap
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "纸筒采购任务-发送sap", notes = "纸筒采购任务-发送sap")
    @GetMapping(value = "/send")
    public Result<Void> send(@RequestParam(name = "id", required = true) String id) {
        paperPurchaseService.send(id);
        return Result.OK();
    }
}
